#!/bin/bash

# FRP 配置自动递增并推送到 Git
# 每次执行会自动对 frpc.ini 进行 +1 操作并推送到远程仓库

set -e  # 遇到错误时退出

# 配置变量
CONFIG_FILE="frpc/frpc.ini"
COMMIT_MESSAGE_PREFIX="auto: increment frpc config"
BRANCH_NAME="master"  # 或者 "main"，根据你的仓库设置

# Git 凭据配置
GIT_USERNAME="yang369875@126.com"
GIT_PASSWORD="16240099yy"
GIT_REMOTE_URL="https://gitee.com/Francesc/noderedinstall.git"

# 默认参数
AUTO_AUTH=false
DRY_RUN=false
NO_BACKUP=false

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Git 状态
check_git_status() {
    print_info "检查 Git 仓库状态..."
    
    # 检查是否在 Git 仓库中
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        print_error "当前目录不是 Git 仓库"
        return 1
    fi
    
    # 检查是否有未提交的更改
    if ! git diff-index --quiet HEAD -- 2>/dev/null; then
        print_warning "检测到未提交的更改，将一并提交"
    fi
    
    # 检查远程仓库连接
    if ! git remote -v | grep -q "origin"; then
        print_error "未配置远程仓库 origin"
        return 1
    fi
    
    return 0
}

# 备份当前配置
backup_config() {
    local backup_file="${CONFIG_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
    cp "$CONFIG_FILE" "$backup_file"
    print_info "备份已创建: $backup_file"
}

# 分析当前配置并进行递增
increment_config() {
    print_info "分析并递增配置文件..."
    
    if [ ! -f "$CONFIG_FILE" ]; then
        print_error "配置文件 $CONFIG_FILE 不存在"
        return 1
    fi
    
    # 读取当前配置
    local ssh_section=$(grep -o '\[ssh[0-9]\+\]' "$CONFIG_FILE" | head -1 | grep -o '[0-9]\+')
    local remote_port=$(grep 'remote_port' "$CONFIG_FILE" | head -1 | grep -o '[0-9]\+')
    local web_section=$(grep -o '\[web[0-9]\+\]' "$CONFIG_FILE" | head -1 | grep -o '[0-9]\+')
    local domain_number=$(grep 'custom_domains.*nodered' "$CONFIG_FILE" | head -1 | grep -o 'nodered[0-9]\+' | grep -o '[0-9]\+')
    
    print_info "当前配置："
    echo "  SSH 段: [ssh$ssh_section] -> 端口: $remote_port"
    echo "  Web 段: [web$web_section] -> 域名: nodered$domain_number"
    
    # 计算新值（处理八进制问题）
    local new_ssh_section=$((10#$ssh_section + 1))
    local new_remote_port=$((10#$remote_port + 1))
    local web_num=$((10#$web_section + 1))
    local domain_num=$((10#$domain_number + 1))
    local new_web_section=$(printf "%03d" $web_num)
    local new_domain_number=$(printf "%03d" $domain_num)
    
    print_info "递增后配置："
    echo "  SSH 段: [ssh$new_ssh_section] -> 端口: $new_remote_port"
    echo "  Web 段: [web$new_web_section] -> 域名: nodered$new_domain_number"
    
    # 使用 Python 进行精确替换
    if command -v python3 >/dev/null 2>&1; then
        python3 << EOF
import re

# 读取文件
with open('$CONFIG_FILE', 'r') as f:
    content = f.read()

# 执行替换
content = re.sub(r'\[ssh\d+\]', '[ssh$new_ssh_section]', content)
content = re.sub(r'remote_port = \d+', 'remote_port = $new_remote_port', content)
content = re.sub(r'\[web\d+\]', '[web$new_web_section]', content)
content = re.sub(r'nodered\d+', 'nodered$new_domain_number', content)

# 写回文件
with open('$CONFIG_FILE', 'w') as f:
    f.write(content)
EOF
    else
        # 手动重写配置文件
        cat > "$CONFIG_FILE" << EOF
[common]
server_addr = sshforems.esunfly.com
server_port = 7000

[ssh$new_ssh_section]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = $new_remote_port

[web$new_web_section]
type = http
local_port = 1880
custom_domains = nodered$new_domain_number.esunfly.com
EOF
    fi
    
    print_success "配置文件已更新"
    
    # 显示新配置
    print_info "更新后的配置："
    cat "$CONFIG_FILE"
    
    # 设置全局变量用于提交消息
    CURRENT_PORT="$new_remote_port"
    CURRENT_DOMAIN="$new_domain_number"
}

# 提交并推送到 Git
commit_and_push() {
    print_info "提交更改到 Git..."
    
    # 确保Git配置存在
    if [ -z "$(git config user.email 2>/dev/null)" ]; then
        print_info "配置Git用户信息..."
        git config user.email "$GIT_USERNAME" 2>/dev/null || true
        git config user.name "yangyang" 2>/dev/null || true
    fi
    
    # 添加配置文件到暂存区
    git add "$CONFIG_FILE"
    
    # 检查是否有其他更改需要提交
    if ! git diff-index --quiet --cached HEAD -- 2>/dev/null; then
        # 创建提交消息
        local commit_msg="$COMMIT_MESSAGE_PREFIX to port $CURRENT_PORT (nodered$CURRENT_DOMAIN)"
        
        # 提交更改
        git commit -m "$commit_msg"
        print_success "已提交: $commit_msg"
        
        # 推送到远程仓库
        print_info "推送到远程仓库..."
        
        # 根据是否启用自动认证来处理推送
        if [ "$AUTO_AUTH" = "true" ]; then
            # 自动认证模式，直接推送
            if git push origin "$BRANCH_NAME"; then
                print_success "✅ 成功推送到远程仓库"
            else
                print_error "❌ 推送失败，请检查网络连接"
                return 1
            fi
        else
            # 手动认证模式，先尝试静默推送，失败则提示
            if git push origin "$BRANCH_NAME" 2>/dev/null; then
                print_success "✅ 成功推送到远程仓库"
            else
                print_warning "推送需要认证，请按提示输入用户名和密码"
                echo "用户名: $GIT_USERNAME"
                echo "密码: $GIT_PASSWORD"
                echo ""
                
                # 再次尝试推送
                if git push origin "$BRANCH_NAME"; then
                    print_success "✅ 成功推送到远程仓库"
                else
                    print_error "❌ 推送失败"
                    print_info "解决方案："
                    print_info "1. 检查网络连接"
                    print_info "2. 确认用户名密码正确"
                    print_info "3. 或运行: ./setup_git_credentials.sh"
                    return 1
                fi
            fi
        fi
    else
        print_warning "没有更改需要提交"
    fi
}

# 显示连接信息
show_connection_info() {
    echo ""
    print_success "=== 部署完成！==="
    echo ""
    echo "🔗 连接信息："
    echo "  SSH 连接: ssh -p $CURRENT_PORT user@sshforems.esunfly.com"
    echo "  Node-RED: http://nodered$CURRENT_DOMAIN.esunfly.com"
    echo ""
    echo "📝 下一步操作："
    echo "  1. 运行安装脚本: sudo ./install_frp.sh"
    echo "  2. 验证服务状态: systemctl status frpc"
    echo "  3. 测试连接"
    echo ""
}

# 显示帮助信息
show_help() {
    echo "=== FRP 配置自动递增和 Git 推送脚本 ==="
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help         显示帮助信息"
    echo "  -d, --dry-run      预览模式（不实际修改和推送）"
    echo "  -b, --branch NAME  指定分支名称（默认: master）"
    echo "  --no-backup        不创建备份文件"
    echo "  --auto-auth        自动配置Git认证（用于一键安装）"
    echo ""
    echo "示例:"
    echo "  $0                 # 正常执行递增和推送"
    echo "  $0 -d              # 预览模式"
    echo "  $0 -b master       # 推送到 master 分支"
    echo "  $0 --auto-auth     # 自动认证并推送"
    echo ""
}

# 预览模式
preview_mode() {
    print_info "=== 预览模式 - 不会实际修改文件 ==="
    
    if [ ! -f "$CONFIG_FILE" ]; then
        print_error "配置文件 $CONFIG_FILE 不存在"
        return 1
    fi
    
    # 读取当前配置
    local ssh_section=$(grep -o '\[ssh[0-9]\+\]' "$CONFIG_FILE" | head -1 | grep -o '[0-9]\+')
    local remote_port=$(grep 'remote_port' "$CONFIG_FILE" | head -1 | grep -o '[0-9]\+')
    local web_section=$(grep -o '\[web[0-9]\+\]' "$CONFIG_FILE" | head -1 | grep -o '[0-9]\+')
    local domain_number=$(grep 'custom_domains.*nodered' "$CONFIG_FILE" | head -1 | grep -o 'nodered[0-9]\+' | grep -o '[0-9]\+')
    
    # 计算新值
    local new_ssh_section=$((10#$ssh_section + 1))
    local new_remote_port=$((10#$remote_port + 1))
    local web_num=$((10#$web_section + 1))
    local domain_num=$((10#$domain_number + 1))
    local new_web_section=$(printf "%03d" $web_num)
    local new_domain_number=$(printf "%03d" $domain_num)
    
    echo ""
    echo "当前配置："
    echo "  [ssh$ssh_section] remote_port = $remote_port"
    echo "  [web$web_section] custom_domains = nodered$domain_number.esunfly.com"
    echo ""
    echo "将要更改为："
    echo "  [ssh$new_ssh_section] remote_port = $new_remote_port"
    echo "  [web$new_web_section] custom_domains = nodered$new_domain_number.esunfly.com"
    echo ""
    echo "Git 提交消息: '$COMMIT_MESSAGE_PREFIX to port $new_remote_port (nodered$new_domain_number)'"
    echo ""
    print_info "要执行实际更改，请运行不带 -d 参数的命令"
}

# 解析命令行参数
DRY_RUN=false
CREATE_BACKUP=true

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -d|--dry-run)
            DRY_RUN=true
            shift
            ;;
        -b|--branch)
            BRANCH_NAME="$2"
            shift 2
            ;;
        --no-backup)
            CREATE_BACKUP=false
            shift
            ;;
        --auto-auth)
            AUTO_AUTH=true
            shift
            ;;
        *)
            print_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
done

# 主程序执行
main() {
    echo "🚀 FRP 配置自动递增和 Git 推送脚本"
    echo "目标分支: $BRANCH_NAME"
    echo ""
    
    # 配置自动认证（如果启用）
    if [ "$AUTO_AUTH" = "true" ]; then
        print_info "配置Git自动认证..."
        
        # 配置用户信息
        git config --global user.email "$GIT_USERNAME" 2>/dev/null || true
        git config --global user.name "yangyang" 2>/dev/null || true
        
        # 直接设置凭据到 .git-credentials
        local credentials_file="$HOME/.git-credentials"
        local encoded_url="https://$(echo -n "$GIT_USERNAME" | sed 's/@/%40/g'):$GIT_PASSWORD@gitee.com"
        
        # 检查是否已经存在相同的凭据
        if [ ! -f "$credentials_file" ] || ! grep -q "gitee.com" "$credentials_file"; then
            echo "$encoded_url" >> "$credentials_file"
            chmod 600 "$credentials_file"
            print_success "Git凭据已自动配置"
        fi
        
        # 启用凭据存储
        git config --global credential.helper store
        print_success "Git自动认证配置完成"
    fi
    
    if [ "$DRY_RUN" = "true" ]; then
        preview_mode
        return 0
    fi
    
    # 检查 Git 状态
    if ! check_git_status; then
        exit 1
    fi
    
    # 创建备份
    if [ "$CREATE_BACKUP" = "true" ]; then
        backup_config
    fi
    
    # 递增配置
    if ! increment_config; then
        exit 1
    fi
    
    # 提交并推送
    if ! commit_and_push; then
        exit 1
    fi
    
    # 显示连接信息
    show_connection_info
}

# 运行主程序
main
